<?php

namespace catchAdmin\registration\controller;

use app\common\model\CollectClass as CollectClassModel;
use catchAdmin\permissions\model\Users as UsersModel;
use catchAdmin\registration\excel\TrialExport;
use catcher\CatchResponse;
use catcher\base\CatchRequest;
use catcher\base\CatchController;
use catcher\exceptions\FailedException;
use app\common\model\PatientInfo as PatientModel;
use app\common\business\Patient as PatientBusiness;
use app\common\model\FollowResultDict as ResultModel;
use catchAdmin\registration\service\TrialService;
use catchAdmin\registration\request\TrialRequest;
use app\common\model\FollowTrial as TrialModel;
use catcher\library\excel\Excel;
use catcher\Utils;
use think\paginator\driver\Bootstrap;
use think\facade\Log;

class TrialFollow extends CatchController
{
    /**
     * 临床实验随访-获取号码维护数据
     *
     * @time 2023年09月04日
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function getTrialFamilyMobile(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();

        if (!isset($req['patientId']) && empty($req['patientId']))
        {
            throw new FailedException("缺少patientId");
        }
        $data = (new PatientBusiness())->getFamilyMembersMobile($req['patientId']);

        $ret = [];
        foreach ($data as $k => $v) {
            $ret[] = [
                'value' => (string)$v['mobile']
            ];
        }
        return CatchResponse::success($ret);
    }

    /**
     * 临床实验随访-获取随访结果数据
     *
     * @time 2023年09月04日
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function getTrialFollowResult(CatchRequest $request): \think\response\Json
    {
        $result = (new ResultModel())->getConditionData([],'name,code');
        $ret = [];
        foreach ($result as $k => $v){
            $ret[] = [
                'resultName' => $v['name'],
                'resultCode' => $v['code']
            ];
        }
        return CatchResponse::success($ret);
    }

    /**
     * 临床实验随访-患者基本信息
     *
     * @time 2023年09月05日
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function getTrialPatientInfo(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        if (empty($req['patientId'])) {
            throw new FailedException("patientId不能为空");
        }
        $where[] = ['patientId', '=', $req['patientId']];
        $field = 'name,sex,medicalRecordsNo,liveStatus,idno,birthdate';
        $ret = (new PatientModel())->getOneData($where, $field);
       
        //患者是否存在
        if (empty($ret)) {
            throw new FailedException("patientId错误");
        }
        $ret['liveStatus'] = $ret['liveStatus']=='1'?'健在':'死亡';
        $birthday = substr($ret['idno'], 6, 8);
        $ret['birthdate'] = date("Y-m-d", strtotime($birthday));
        //$ret['medicalRecordsNo'] = $ret['inList']['medicalRecordsNo']??'';
        return CatchResponse::success($ret);
    }

    /**
     * 列表
     * @time 2023年09月04日
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function index(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        $user = request()->user();
        $where = [];

        //获取角色标识
        $roles = (new UsersModel())->currentUserRoleInfo($user['id'], 'role.identify')->column('identify');
      #  Log::write("角色标识：".json_encode($roles));           
        $identify = ['admin','lcsyglry','yyxtgly','lcsysfry'];

        //判断是否存在能看随访记录的角色
        if (empty(array_intersect($roles, $identify))) {
            return CatchResponse::paginate(Bootstrap::make([],15, 1, 0));
        }

        //临床试验随访人员只能看自己的随访记录
        if (in_array('lcsysfry', $roles) && empty(array_intersect($roles, ['admin','lcsyglry','yyxtgly']))) {
            $where[] = ['creator_id', '=', $user['id']];
            Log::write("临床试验随访记录进来了", "info"); 
        }

        if (!empty($req['patientId'])) {
            $where[] = ['patientId', '=', $req['patientId']];
        }

        $list = (new TrialModel())->getList($where);

        $list = $list->append(["status_text"]);
        return CatchResponse::paginate($list);
    }

    /**
     * 保存
     *
     * @time 2023年09月04日
     * @param TrialRequest $request
     * @return \think\response\Json
     */
    public function save(TrialRequest $request): \think\response\Json
    {
        $req = $request->param();
        return CatchResponse::success((new TrialService())->saveTrialFollow($req));
    }

    /**
     * 更新
     *
     * @time 2020年01月09日
     * @param $id
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function update($id, CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        $info = (new TrialModel())->where('id', $id)->field('pid,status')->find();
        if (!empty($req['result'])) {
            foreach ($req['result'] as $k => $v) {
                if($v['code'] == 19) {
                    $patientData = [];
                    $req['liveStatus'] = '0';
                    $req['liveStatusText'] = '死亡';
                    $patientData['liveStatus'] = '0';
                    if (!isset($req['deathDate'])) {
                        throw new FailedException("缺少死亡时间");
                    }
                    $patientData['deathDate'] = $req['deathDate'];
                    (new CollectClassModel())->pullNode([$info['pid']]);
                    (new PatientModel())->saveData($info['pid'], $patientData);
                }
            }
        }

        //审批同意状态下，不更改状态
        if ($info['status'] !== 3) {
            $req['status'] = 0;
        }

        (new TrialService())->recordOperationLogs(1,1,$id);
        return CatchResponse::success((new TrialModel())->saveData($id, $req));
    }

    /**
     * 删除
     *
     * @time 2020年01月09日
     * @param $id
     * @return \think\response\Json
     */
    public function delete($id): \think\response\Json
    {
        (new TrialService())->recordOperationLogs(1,2,$id);
        return CatchResponse::success((new TrialModel())->destroy($id));
    }

    /**
     * 导出
     *
     * @time 2020年09月08日
     * @param Excel $excel
     * @param TrialExport $trialExport
     * @return \think\response\Json
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     */
    public function export(Excel $excel, TrialExport $trialExport)
    {
        $req = request()->param();
        if (empty($req['title'])) {
            throw new FailedException("请传入title");
        }
        return CatchResponse::success($excel->save($trialExport, Utils::publicPath('export/trials')));
    }

    /**
     * 打印操作记录
     *
     * @time 2023年10月31日
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function trialPrintLog(CatchRequest $request): \think\response\Json
    {
        $mode = $request->param('mode');
        $id = $request->param('id');
        return CatchResponse::success((new TrialService())->recordOperationLogs($mode,3,$id));
    }

    /**
     * 审批
     * @time 2023年11月24日
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function approval(CatchRequest $request): \think\response\Json
    {
        $req = $request->only(['id', 'status']);
        if (!isset($req['id']) || $req['id'] === '' || !isset($req['status']) || $req['status'] === '') {
            throw new FailedException('id和status不能为空');
        }

        // 验证参数类型
        if (!is_string($req['id']) || !is_int($req['status'])) {
            throw new FailedException('参数类型错误');
        }

        $ret = (new TrialService())->approvalOperation($req['id'], $req['status']);
        return CatchResponse::success($ret);
    }
}
